﻿using Coldairarrow.Entity.DTO;
using Coldairarrow.IBusiness;
using Coldairarrow.IBusiness.Ocr;
using Coldairarrow.Util;
using Coldairarrow.Util.ClassLibrary;
using Coldairarrow.Util.Helper;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace Coldairarrow.Business.Ocr
{
    public class Ocr_AnalysisBusiness : IOcr_AnalysisBusiness, ITransientDependency
    {
        readonly IOperator _operator;
        public Ocr_AnalysisBusiness(IOperator @operator)
        {
            _operator = @operator;
        }
        public async Task<string> GetLicensePlateAsync(string clientId, string clientSecret, string url, RedisOptions _redisOptions) 
        {
            #region 获取百度Token
            //查看Redis里是否有此配置
            _redisOptions.DbChannel = (int)Redis_Type.redis2;
            RedisSetHelper redis = new RedisSetHelper(_redisOptions);
            string ocrToken = redis.GetString("BaiduOcr");
            //如果没有则调取接口
            if (ocrToken.IsNullOrEmpty())
            {
                String authHost = "https://aip.baidubce.com/oauth/2.0/token";
                HttpClient client = new HttpClient();
                List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
                paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
                paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                var response = await client.PostAsync(authHost, new FormUrlEncodedContent(paraList));
                //HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
                String result = response.Content.ReadAsStringAsync().Result;
                JObject jo = JObject.Parse(result);
                //获取Token错误
                if (result.IndexOf("error_description") > -1)
                {
                    return jo["error_description"].ToString();
                }
                //写String 缓存token的有效秒
                redis.SetString("BaiduOcr", jo["access_token"].ToString(), TimeSpan.FromSeconds(Convert.ToInt32(jo["expires_in"].ToString())));
                ocrToken = jo["access_token"].ToString();
            }
            #endregion

            #region 解析车牌
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + ocrToken;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            // 图片的base64编码
            string base64 = getFileBase64(url);
            String str = "image=" + HttpUtility.UrlEncode(base64);
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse resPhoto = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resPhoto.GetResponseStream(), Encoding.Default);
            string resultPlate = reader.ReadToEnd();
            JObject jom = JObject.Parse(resultPlate);
            string plate = jom["words_result"]["number"].ToString();
            return plate;
            #endregion
        }
                
        /// <summary>
        /// 获取文件并转base64
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static String getFileBase64(String fileName)
        {
            FileStream filestream = new FileStream(fileName, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }
    }
}
